package org.marlin.http.server;

import org.marlin.http.http.Parameter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


/**
 * init version 1.5.0
 * @author Jack ZG
 * @since 1.0.0
 */
public class ServerBean<S> {
    private Parameter[] paramNames;
    private Map<String, Parameter> parameterMap = new HashMap<>();
    private Method method;
    private S service;

    public ServerBean(Parameter[] paramNames, Method method) {
        this.paramNames = paramNames;
        this.method = method;
    }

    public Parameter[] getParamNames() {
        return this.paramNames;
    }

    public void setParamNames(Parameter[] paramNames) {
        for (Parameter parameter : paramNames) {
            this.parameterMap.put(parameter.getName(), parameter);
        }
    }

    public Method getMethod() {
        return this.method;
    }

    public void setMethod(Method method) {
        this.method = method;
    }

    public Object invoke() throws InvocationTargetException, IllegalAccessException {
        Object invoke = this.method.invoke(this.service, getParams());
        return invoke;
    }

    private Object[] getParams() {
        Object[] objects = new Object[this.paramNames.length];
        for (int i = 0, size = this.paramNames.length; i < size; i++) {
            Parameter parameter = this.parameterMap.get(this.paramNames[i].getName());
            objects[i] = (parameter == null) ? null : parameter.getValue();
        }
        return objects;
    }
}

